import java.util.Arrays;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * @FileName Solution16
 * @Description
 * @Author tong.zhou
 * @date 2025-04-12
 **/
public class Solution16 {

    private int getBest(Integer best, Integer target, int a, int b, int c){
        Integer bestSub = Math.abs(best - target);
        Integer tmpSub = Math.abs((a + b + c) - target);
        if(tmpSub < bestSub){
            return a + b + c;
        }
        return best;
    }

    private int getClosestCByBinarySearch(int[] nums, int target, int fromInd) {
        int left = fromInd;
        int right = nums.length - 1;

        // 标准二分查找模板
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        Integer celling = nums[left];
        Integer floor = left - 1 >= fromInd ? nums[left - 1] : null;
        if (floor == null) {
            return celling;
        }
        if (Math.abs(celling - target) < Math.abs(target - floor)) {
            return celling;
        }
        return floor;
    }

    public int threeSumClosest(int[] nums, int target) {
        // 将int数组转为TreeSet（自动排序+去重）
        Arrays.sort(nums);
        Integer best = Integer.MAX_VALUE;
        for (int i = 0; i < nums.length; i++) {
            int a = nums[i];
            for (int j = i + 1; j < nums.length - 1; j++) {
                int b = nums[j];
                int tmpTarget = target - a - b;
                Integer closestC = getClosestCByBinarySearch(nums, tmpTarget, j + 1);
                best = getBest(best, target, a, b, closestC);
            }
        }
        return best;
    }

    public static void main(String[] args) {
        Solution16 solution16 = new Solution16();
        solution16.threeSumClosest(new int[]{-1,2,1,-4}, 1);
    }
}
